<?php
/**
 * Created by PhpStorm.
 * User: bolle
 * Date: 25.12.15
 * Time: 10:31
 */

namespace tbollmeier\alteraparser\syntaxgraph;


class Multiples extends VertexGroup
{

    private $element;
    private $minOccur;
    private $maxOccur;

    public function __construct($element, $minOccur=0, $maxOccur=null)
    {
        parent::__construct();

        $this->element = $element !== null ? $element->copy() : null;
        $this->minOccur = $minOccur;
        $this->maxOccur = $maxOccur;
    }

    protected function onExpand(&$start, &$end)
    {
        assert($this->element !== null);

        $current = $start;
        for ($i=0; $i<$this->minOccur; $i++) {
            $current = $current->connect($this->element->copy());
        }
        $minEnd = $current;
        if ($this->maxOccur === null) {
            if ($current !== $start) {
                $current->connect($current);
            } else {
                $element = $this->element->copy();
                $start->connect($element)->connect($start);
                $element->connect($end);
            }
        } else {
            $delta = $this->maxOccur - $this->minOccur;
            for ($i=0; $i<$delta; $i++) {
                $current = $current->connect($this->element->copy());
                $current->connect($end);
            }
        }

        $minEnd->connect($end);

    }

    protected function onCopy($original)
    {
        parent::onCopy($original);

        $this->element = $original->element !== null ? $original->element->copy() : null;
        $this->minOccur = $original->minOccur;
        $this->maxOccur = $original->maxOccur;
    }

}